package com.lxw.weather.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;
import com.lxw.weather.BuildConfig;
import com.lxw.weather.R;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UpdateManager {
    private Context mContext;
    private static final String VERSION_URL = "https://gitee.com/lu-xingwang609216/weather_app_update/raw/main/version.json";

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    public void checkUpdate() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(VERSION_URL).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showToast("版本检查失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful() && response.body() != null) {
                    try {
                        JSONObject json = new JSONObject(response.body().string());
                        String latestVersion = json.getString("versionName");
                        int latestCode = json.getInt("versionCode");
                        String downloadUrl = json.getString("downloadUrl");

                        // 对比版本号
                        if (latestCode > BuildConfig.VERSION_CODE) {
                            showUpdateDialog(latestVersion, downloadUrl);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        showToast("版本信息解析失败");
                    }
                }
            }
        });
    }

    private void showUpdateDialog(String version, String url) {
        ((Activity) mContext).runOnUiThread(() -> {
            new AlertDialog.Builder(mContext)
                .setTitle("发现新版本 v" + version)
                .setMessage("是否立即更新？")
                .setPositiveButton("更新", (dialog, which) -> downloadApk(url))
                .setNegativeButton("取消", null)
                .setCancelable(false)
                .show();
        });
    }

    private void downloadApk(String url) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url))
            .setTitle("天气APP更新")
            .setDescription("正在下载新版本...")
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "weather_update.apk");

        DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
        showToast("开始下载更新");
    }

    private void showToast(String message) {
        ((Activity) mContext).runOnUiThread(() ->
            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show()
        );
    }
}